package com.steven.nio;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileOperate {
	private static String filePath = "src/com/steven/nio/nio.txt";
	public static void io() {
		InputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(filePath));
			
			byte[] buf = new byte[1024];
			int len = 0;
			while((len = in.read(buf)) != -1) {
				for(int i=0; i<len; i++) {
					System.out.print((char)buf[i]);
				}
			}
		} catch (Exception e) {
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 
	 * @Description: 
	 * 		Buffer维护四个变量: 
	 * 			position		下个操作元素的位置
	 * 			limit			当前能从缓冲区读取多少元素。即缓冲区不可操作的下个元素的位置
	 * 			capacity		缓冲区数组的长度
	 * 			mark			用于记录当前position的前一个位置或默认是0
	 * 
	 * @author hzg
	 * 
	 * @Note
	 * <br><b>Date:</b> 2018年1月5日 下午4:59:33
	 *
	 * @param
	 */
	public static void nio() {
		RandomAccessFile file = null;
		try {
			file = new RandomAccessFile(filePath, "rw");
			FileChannel channel = file.getChannel();
			ByteBuffer buf = ByteBuffer.allocate(1024);	// 分配缓冲区空间
			// ByteBuffer.allocateDirect(1024);
			
			int len = 0;
			while ((len = channel.read(buf)) != -1) {	// 从通道中读取数据到缓冲区
				buf.flip();		// limit=position;position=0;mark=-1;
				while (buf.hasRemaining()) {
					System.out.println((char)buf.get());
				}
				buf.compact();		// 把未读的数据拷贝到buffer的起始处
			}
			System.out.println(len);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (file != null) {
				try {
					file.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		io();
	}
}
